<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Speaker;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Tab;

class SpeakerController extends AdminController
{

    // public function index(Content $content): Content
    // {
    //     $tab = Tab::make();
    //     $tab->add('文件存储', new \Weiwait\DcatVue\Forms\FilesystemConfig());

    //     return $content->title('配置')
    //         ->body($tab->withCard());
    // }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Speaker(), function (Grid $grid) {

            // $grid->scrollbarX();
            $grid->withBorder();
            $grid->addTableClass(['table-text-center']);


            $grid->showColumnSelector();
            if (Admin::user()->can('speaker-library-export')) {
                $grid->export();
                // $grid->disableQuickCreateButton();
            }


            $grid->column('id')->sortable();
            $grid->name->filter()->sortable();

            $grid->status()->radio(['未审核', '已审核', '驳回']);
            // $grid->column('review_comments', '审核意见')->editable(true);

            $grid->photo()->customImage();
            $grid->email->label()->filter();
            $grid->column('country');
            $grid->column('time_zone');
            // $grid->column('institution');
            // $grid->column('areas_of_expertise');
            // $grid->column('medical_category');
            // $grid->column('presenting_meeting');
            // $grid->column('research_sponsor');
            // $grid->column('association');
            // $grid->column('journal_position');
            // $grid->column('information_website');
            $grid->column('photo')->customImage();
            // $grid->column('local_photo');
            // $grid->column('small');
            $grid->column('email');
            // $grid->column('note');
            // $grid->column('create_time');
            // $grid->column('update_time');
            // $grid->column('sort');
            // $grid->column('status');
            // $grid->column('is_del');
            // $grid->column('user_id');
            // $grid->column('review_comments');
            // $grid->column('admin_id');
            $grid->column('created_at');
            // $grid->column('updated_at')->sortable();
            $grid->model()->orderBy('id', 'desc');
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
            });


            /**
             * 按钮控制.
             */
            // @permissions
            if (!Admin::user()->can('speaker-library-create')) {
                $grid->disableCreateButton();
                // $grid->disableQuickCreateButton();
            }
            // @permissions
            if (!Admin::user()->can('speaker-library-update')) {
                $grid->disableEditButton();
                // $grid->disableQuickEditButton();
            }
            // @permissions
            if (!Admin::user()->can('speaker-library-delete')) {
                $grid->disableDeleteButton();
            }
            // @permissions
            if (!Admin::user()->can('speaker-library-view')) {
                $grid->disableViewButton();
            }

            $grid->quickSearch(function ($model, $query) {
                $model->where('name',  'like', "%{$query}%")
                    ->orWhere('country', 'like', "%{$query}%")
                    ->orWhere('time_zone', 'like', "%{$query}%")
                    ->orWhere('institution', 'like', "%{$query}%")
                    ->orWhere('areas_of_expertise', 'like', "%{$query}%")
                    ->orWhere('medical_category', 'like', "%{$query}%")
                    ->orWhere('presenting_meeting', 'like', "%{$query}%")
                    ->orWhere('research_sponsor', 'like', "%{$query}%")
                    ->orWhere('association', 'like', "%{$query}%")
                    ->orWhere('journal_position', 'like', "%{$query}%")
                    ->orWhere('information_website', 'like', "%{$query}%");
            })->placeholder('全局搜索');
            $grid->filter(function (Grid\Filter $filter) {
                // $filter->equal('id');
                $filter->like('name');
                $filter->like('country');
                $filter->like('time_zone');
                $filter->like('institution');
                $filter->like('areas_of_expertise', '擅长领域');
                $filter->like('medical_category');
                $filter->like('presenting_meeting');
                $filter->like('research_sponsor');
                $filter->like('association');
                $filter->like('journal_position');
                $filter->like('information_website');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Speaker(), function (Show $show) {
            if (!Admin::user()->can('speaker-list-delete')) {
                $show->disableDeleteButton();
            }

            // @permissions
            if (!Admin::user()->can('speaker-list-update') || (Admin::user()->id != $show->model()->admin_id) && !Admin::user()->isAdministrator() || ($show->model()->status == 1 && !Admin::user()->isAdministrator())) {
                $show->disableEditButton();
            }
            $show->field('id');
            $show->field('name');
            $show->field('time_zone', '时差、时区');
            $show->field('institution', '就职机构及任职');
            $show->field('areas_of_expertise', '擅长领域');
            $show->field('medical_category', '医疗领域');
            $show->field('presenting_meeting', '会议演讲及题目');
            $show->field('research_sponsor', '演讲研究赞助商');
            $show->field('association', '学协会及任职');
            $show->field('journal_position', '期刊及任职及影响因子');
            $show->field('information_website', '信息来源网页');

            $show->photo()->image();
            $show->field('email');
            $show->field('note', '备注');
            // $show->field('create_time');
            // $show->field('update_time');
            $show->field('sort', '排序');
            // $show->field('status');
            // $show->field('is_del');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Speaker(), function (Form $form) {
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableCreatingCheck();

            // @permissions
            if (!Admin::user()->can('speaker-list-delete')) {
                $form->disableDeleteButton();
            }
            $form->display('id');

            $form->vImage('photo') // 关联文件系统配置-直传-裁剪
                ->ratio([16 / 9, 4 / 3]) // 固定裁剪比例
                // ->large() // 放大裁剪框
                ->resolution(1920, 1080) // 重置图片分辨率
                ->jpeg(0.8) // 裁剪为jpeg格式, 参数为图片质量0-1
                ->disableCropper() // 关闭裁剪弹窗
                ->mimeTypes('image/*');

            $form->array('擅长领域', function ($table) {
                $table->text('cn', '中文');
                $table->text('en', '英文');
                // $table->textarea('desc');
            })->saveAsJson();
            $form->text('name')->help('一般为Prof. 开头加姓名。例： Prof. Piet Hu');
            $form->text('country')->help('城市，缩写（如有），国家。例：San Francisco, CA, USA');
            $form->text('time_zone', '时差')->help('时区名称（世界标准名称），与北京时间时差xx小时。例：PDT (UTC -7) ，时差-15个小时');
            $form->textarea('institution', '就职机构及任职')->help('机构职位，机构；（多个用分号隔开）。例：Associate Dean for Translational Research, University of Pennsylvania Perelman School of Medicine;
Director, Institute for Translational Medicine and Therapeutics, University of Pennsylvania Perelman School of Medicine;
Senior Advisor to the EVP and Dean, University of Pennsylvania Perelman School of Medicine;');
            $form->textarea('areas_of_expertise', '擅长领域')->help('例：prostanoid biology and the role of peripheral molecular clocks in cardiovascular biology, metabolism and aging.');
            $form->text('medical_category', '医疗领域')->help('大领域或细分领域。例：乳腺癌');
            $form->textarea('presenting_meeting', '会议演讲及题目')->help('会议名称，摘要编号：摘要题目；（多个用分号分开）。例：ASCO 2022, Abstract 1000: Trastuzumab deruxtecan (T-DXd) versus trastuzumab emtansine (T-DM1) in patients (pts) with HER2-positive (HER2+) unresectable and/or metastatic breast cancer (mBC): Safety follow-up of the randomized, phase 3 study DESTINY-Breast03.');
            $form->textarea('research_sponsor', '演讲研究赞助商')->help('多个用分号分开。例：Daiichi Sankyo; AstraZeneca');
            $form->textarea('association', '学协会及任职')->help('学协会任职，学协会；（多个用分号分开）。例：Co-chair, Triple Negative Working Group; member, Translational Breast Cancer Research Consortium (TBCRC); Guidelines Committee member, Education Committee of ASCO;');
            $form->textarea('journal_position', '期刊及任职及影响因子')->help('期刊任职，期刊（影响因子）；（多个用分号分开）。例：Chief Scientific Advisors, Science Translational Medicine (19.319)；');

            $form->image('photo')->autoUpload()->move('speaker/photo/' . date('Y/m'))->help('添加照片');
            $form->email('email')->help('添加邮箱');
            $form->textarea('information_website', '信息来源网页')->help('添加信息来源网页，多个的用回车分开。例：https://www.itmat.upenn.edu/faculty-fitzgerald.html; https://www.med.upenn.edu/apps/faculty/index.php/g275/p9400;');
            $form->editor('note', '备注')->help('任何信息均可备注，例如已经参加过我们项目的')->languageUrl(url('TinyMCE/langs/zh_CN.js'));
            // $form->text('create_time');
            // $form->text('update_time');
            $form->text('sort', '排序');
            $form->tags('tags', '自定义标签')->saving(function ($value) {
                return implode(',', $value);
            })->help('输入标签后空格+回车');
            // $form->hidden('admin_id')->value(Admin::user()->id);
            $form->hidden('review_comments');
            // dd($form->status);
            $form->hidden('status')->value(0)
                ->customFormat(function ($v) {
                    return $v == 1 ? 1 : 0;
                })
                ->saving(function ($v) {
                    return $v;
                });
            // //表单先隐藏缩略图
            // $form->hidden('small');
            // //上传图片 并生成相应缩略图
            // //保存前获取 缩略图地址 并给表单赋值
            // $form->saving(function (Form $form) {
            //     if ($form->photo) {
            //         $small = explode(".", $form->photo);
            //         $form->small = $small[0] . '-small.' . $small[1];
            //     }
            // });
            // if ($form->isDeleting()) {
            //     AdminUploadInfoService::deleteUploadLogs(['type_name' => 'foreign', 'fk_info_id' => $form->getKey()]);
            // }
            // $result 是添加成功后的主键id 修改是表示成功的 1
            // $form->saved(function (Form $form, $result) {
            // $speaker_info = ModelsForeignSpeaker::find($result);
            // if ($form->isCreating()) {
            // 添加上传记录
            // AdminUploadInfoService::saveUploadLogs(
            //     [
            //         'title' => '新增外籍讲者 《' . $speaker_info['name'] . '》',
            //         'type_name' => 'foreign',
            //         'fk_info_id' => $result,
            //         'admin_id' => Admin::user()->id,
            //         'status' => 0,
            //     ]
            // );
            // }

            // if ($form->isEditing()) {
            // // 修改状态
            // AdminUploadInfoService::setStatus(
            //     [
            //         'type_name' => 'foreign',
            //         'fk_info_id' => $form->model()->id,
            //         // 'admin_id' => Admin::user()->id
            //     ],
            //     $form->model()->status
            // );
            //     if (!empty($form->model()->review_comments)) {
            //         ModelsForeignSpeaker::setReviewComments($form->model()->id, [
            //             'review_comments' => $form->model()->review_comments
            //         ]);
            //     }
            // }
            // });
        });
    }
}
